//
//  ZYTencentHandler.m
//  SuiTong
//
//  Created by 石志愿 on 2020/9/3.
//  Copyright © 2020 石志愿. All rights reserved.
//

#import "ZYTencentHandler.h"

#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterfaceObject.h>
#import <TencentOpenAPI/QQApiInterface.h>

@interface ZYTencentHandler ()<TencentSessionDelegate, QQApiInterfaceDelegate>

@property (nonatomic, strong) TencentOAuth *tencentOAuth;

/// 登录回调
@property (nonatomic, copy) ZYThirdLoginBlock loginCompletion;
/// 分享回调
@property (nonatomic, copy) ZYThirdShareBlock shareCompletion;

@end

@implementation ZYTencentHandler

//MARK: public

- (void)registerApp {
    self.tencentOAuth = [[TencentOAuth alloc]initWithAppId:kQQAppKey andUniversalLink:kQQUniversalLink andDelegate:self];
}

- (BOOL)installQQ {
    return [TencentOAuth iphoneQQInstalled];
}

+ (BOOL)HandleOpenURL:(NSURL *)url {
    return [TencentOAuth HandleOpenURL:url];
}

//处理应用的UniversalLink拉起协议
+ (BOOL)handleUniversalLink:(NSURL *)url {
    return [TencentOAuth HandleUniversalLink:url];
}

//MARK: 分享

// 分享网页
- (void)shareWebPage:(ZYThirdShareInfo *)info platform:(ZYSharePlatform)platform completion:(__nullable ZYThirdShareBlock)completion {
    if ([NSString isEmpty:info.url]) {
        [MBProgressHUD showMessage:@"分享链接不能为空"];
        return;
    }
    NSURL *url = [NSURL URLWithString:info.url];
    if (!url) {
        [MBProgressHUD showMessage:@"分享链接错误"];
        return;
    }
    
    if ([NSString isEmpty:info.title]) {
        info.title = @"邃瞳";
    }
    
    if ([NSString isEmpty:info.desc]) {
        info.desc = @"邃瞳分享";
    }
    
    NSData *imageData = nil;
    if (info.icon) {
        imageData = [info.icon compressWithMaxWidth:100 maxSizeKB:10];
    } else {
        UIImage *image = [UIImage imageNamed:@"share_logo"];
        if (image) {
            imageData = UIImageJPEGRepresentation(image, 1.0);
        }
    }
    QQApiNewsObject *message = [[QQApiNewsObject alloc]initWithURL:url title:info.title description:info.desc previewImageData:imageData targetContentType:QQApiURLTargetTypeNews];
    [self sendShare:message platform:platform completion:completion];
}

//分享图片, 仅支持QQ好友
- (void)shareImage:(UIImage *)image thumbImage:(UIImage *)thumbImage  completion:(__nullable ZYThirdShareBlock)completion {
    if (!image) {
        return;
    }
    if (!thumbImage) {
        return;
    }
    NSData *imageData = UIImageJPEGRepresentation(image, 0.7);
    NSData *thumbData = UIImageJPEGRepresentation(thumbImage, 0.7);
    QQApiImageObject *object = [[QQApiImageObject alloc]initWithData:imageData previewImageData:thumbData title:@"" description:@""];
    [self sendShare:object platform:ZYSharePlatformQQ completion:completion];
}

//分享文本, 仅支持QQ好友
- (void)shareText:(NSString *)text completion:(__nullable ZYThirdShareBlock)completion {
    QQApiTextObject *obj = [[QQApiTextObject alloc]initWithText:text];
    [self sendShare:obj platform:ZYSharePlatformQQ completion:completion];
}

- (void)sendShare:(QQApiObject *)content platform: (ZYSharePlatform)platform completion:(__nullable ZYThirdShareBlock)completion {
    self.shareCompletion = completion;
    SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:content];
    if (platform == ZYSharePlatformQQ) {
        [QQApiInterface sendReq:req];
    } else if (platform == ZYSharePlatformQzone) {
        [QQApiInterface SendReqToQZone:req];
    }
}

//MARK: 登录
- (void)login:(__nullable ZYThirdLoginBlock)completion {
    self.loginCompletion = completion;
    NSArray* permissions = [NSArray arrayWithObjects:kOPEN_PERMISSION_GET_USER_INFO,kOPEN_PERMISSION_GET_SIMPLE_USER_INFO,nil];
    BOOL inSafari = ![self installQQ];
    [self.tencentOAuth authorize:permissions inSafari:inSafari];
}

//MARK: QQApiInterfaceDelegate

/**
 处理来至QQ的请求
 */
- (void)onReq:(QQBaseReq *)req {
    
}

/**
 处理来至QQ的响应
 */
- (void)onResp:(QQBaseResp *)resp {
    if ([resp isKindOfClass:SendMessageToQQResp.class]) {
        SendMessageToQQResp *newRes = (SendMessageToQQResp *)resp;
        if ([newRes.result isEqualToString:@"0"]) {
            if (self.shareCompletion) {
                self.shareCompletion(ZYShareStatusSuccess);
            }
        } else if ([newRes.result isEqualToString:@"-4"]) {
            if (self.shareCompletion) {
                self.shareCompletion(ZYShareStatusCancel);
            }
        } else {
            if (self.shareCompletion) {
                self.shareCompletion(ZYShareStatusFailed);
            }
        }
    }
}

/**
 处理QQ在线状态的回调
 */
- (void)isOnlineResponse:(NSDictionary *)response {
    
}

//MARK: TencentSessionDelegate

/// 登录成功后的回调
- (void)tencentDidLogin {
    if (![NSString isEmpty:self.tencentOAuth.accessToken]) {
        [self.tencentOAuth getUserInfo];
    }
}

/// 登录失败后的回调
- (void)tencentDidNotLogin:(BOOL)cancelled {
    if (cancelled) {
        if (self.loginCompletion) {
            self.loginCompletion(nil, ZYShareStatusCancel);
        }
    } else {
        if (self.loginCompletion) {
            self.loginCompletion(nil, ZYShareStatusFailed);
        }
    }
}

/// 获取用户个人信息回调
- (void)getUserInfoResponse:(APIResponse *)response {
    if (response.retCode == 0) {
        NSDictionary *res = response.jsonResponse;
        ZYThirdLoginInfo *info = [ZYThirdLoginInfo mj_objectWithKeyValues:res];
        info.platform = ZYThirdLoginPlatformQQ;
        info.imageUrl = res[@"figureurl_qq_2"];
        if (self.loginCompletion) {
            self.loginCompletion(info, ZYShareStatusSuccess);
        }
    } else {
        [MBProgressHUD showMessage:@"获取授权信息异常"];
    }
}

/// 登录时网络有问题的回调
- (void)tencentDidNotNetWork {
    
}

@end
